1362E - Johnny and Grandmaster - CodeForces Solution


data structures greedy implementation math number theory sortings two pointers *1900

Please click on ads to support us..

Python Code:

import sys
from heapq import *

input = lambda: sys.stdin.buffer.readline().decode().rstrip()



mod = 10**9 + 7

def solve():
    n ,p = list(map(int,input().split()))
    arr = list(map(int,input().split()))
    if p == 1 : 
        print(n%2) 
        return
    ans = 0 
    h= [ -i for i in arr] 

    heapify(h) 
    cnt = {}
    nonzero = [] 
    
    while h : 
        ai = -heappop(h)
        try:
            cnt[ai] += 1 
        except :
            cnt[ai] = 1
        heappush(nonzero,-ai) 
        while nonzero and cnt[-nonzero[0]]%2 == 0 : 
            cnt[-nonzero[0]] = 0 
            heappop(nonzero) 
            
        if cnt[ai] : 
            if cnt[ai] == p : 
                cnt[ai] = 0 
                heappush(h,-(ai+1)) 
    f = False

    for i in sorted(cnt.keys(),reverse=1) :
        if cnt[i] :
            if f :
                ans -= cnt[i]*pow(p,i,mod)
            else:
                f = True
                ans += pow(p,i,mod)
            ans %= mod 
    print(ans)
 
for t in range(int(input())):
        solve()


Comments

Submit
0 Comments
More Questions

1536A - Omkar and Bad Story
1509A - Average Height
1506C - Double-ended Strings
340A - The Wall
377A - Maze
500A - New Year Transportation
908D - New Year and Arbitrary Arrangement
199A - Hexadecimal's theorem
519C - A and B and Team Training
631A - Interview
961B - Lecture Sleep
522A - Reposts
1166D - Cute Sequences
1176A - Divide it
1527A - And Then There Were K
1618E - Singers' Tour
1560B - Who's Opposite
182B - Vasya's Calendar
934A - A Compatible Pair
1618F - Reverse
1684C - Column Swapping
57C - Array
1713D - Tournament Countdown
33A - What is for dinner
810A - Straight A
1433C - Dominant Piranha
633A - Ebony and Ivory
1196A - Three Piles of Candies
299A - Ksusha and Array
448B - Suffix Structures